package cn.zl.ymcc.service.impl;

import cn.zl.ymcc.constant.treeConstant;
import cn.zl.ymcc.entity.CourseType;
import cn.zl.ymcc.mapper.CourseTypeMapper;
import cn.zl.ymcc.service.CourseTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import io.swagger.v3.oas.annotations.tags.Tag;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author zl
 * @since 2025-10-21
 */

@Tag(name = "CourseType服务实现")

@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements CourseTypeService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<CourseType> tree() {
        Object o = redisTemplate.opsForValue().get(treeConstant.COURSE_TYPE_DATA);
        if (o != null) {
            return (List<CourseType>) o;
        }
        List<CourseType> list = list();
        Map<Long, CourseType> map = new HashMap<>();
        for (CourseType courseType : list) {
            map.put(courseType.getId(), courseType);
        }
        list.forEach(courseType -> {
            CourseType courseType1 = map.get(courseType.getPid());
            if (courseType1 != null) {
                courseType1.getChildren().add(courseType);
            }
        });
        List<CourseType> list1 = list.stream().filter(courseType -> courseType.getPid() == 0).collect(Collectors.toList());
        redisTemplate.opsForValue().set(treeConstant.COURSE_TYPE_DATA, list1);
        return list1;

    }

    @Override
    public boolean save(CourseType entity) {
        redisTemplate.delete(treeConstant.COURSE_TYPE_DATA);
        return super.save(entity);
    }
}
